/**
 * $Id: UserServiceImpl.java 23 2011-06-15 13:58:35Z feigme $
 */
package com.iary.domain.service.impl;

import org.apache.commons.validator.GenericValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.iary.domain.model.user.User;
import com.iary.domain.model.user.UserExistedException;
import com.iary.domain.model.user.UserLoginInfo;
import com.iary.domain.model.user.UserRepository;
import com.iary.domain.service.UserService;
import com.iary.infrastructure.orm.Page;

@Component
public class UserServiceImpl implements UserService {

	private UserRepository userRepository;

	UserServiceImpl() {

	}

	@Autowired
	public UserServiceImpl(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	public boolean isExistedEmail(String email) {
		User user = userRepository.findUserByEmail(email);
		return user == null ? false : true;
	}

	public boolean isExistedUserName(String userName) {
		User user = userRepository.findUserByUserName(userName);
		return user == null ? false : true;
	}

	public Long registerUser(String email, String userName, String password)
			throws UserExistedException {
		if (isExistedEmail(email)) {
			throw new UserExistedException("email is existed.");
		}
		if (isExistedUserName(userName)) {
			throw new UserExistedException("userName is existed");
		}
		User user = new User(new UserLoginInfo(email, userName, password));
		userRepository.save(user);
		return user.getId();
	}

	public User findUserByUserNameOrEmail(String userNameOrEmail) {
		if (GenericValidator.isEmail(userNameOrEmail)) {
			return userRepository.findUserByEmail(userNameOrEmail);
		} else {
			return userRepository.findUserByUserName(userNameOrEmail);
		}
	}

	public Page<User> findAllUser(Page<User> page) {
		return userRepository.getAll(page);
	}

}
